﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PSE.Framework.ProviderLoader.Configuration;
using PSE.Framework.Configuration;
using PSE.Framework.ProviderLoader;

namespace PSE.Framework.UI.Settings
{
    public static class ConfigurationSettingsManager<TConfigurationObjectType>
        where TConfigurationObjectType : struct
	{
		/// <summary>
		/// Captura o provider de settings atual
		/// </summary>
        public static IConfigurationSettings<TConfigurationObjectType> GetConfigurationSettings()
		{
			// Tenta capturar provider remoto
            IConfigurationSettings<TConfigurationObjectType> config = GetServerConfigurationSettings();

			// Se não existir provider remoto, captura provider local
			if (config == null)
			{
				config = GetLocalConfigurationSettings();
			}

			return config;
		}

		/// <summary>
		/// Retorna o provider de settings local
		/// </summary>
		/// <returns>Provider de settings</returns>
        public static IConfigurationSettings<TConfigurationObjectType> GetLocalConfigurationSettings()
		{
            ProviderConfigurationSection configSection = ApplicationConfiguration.GetCurrent().GetSection<ProviderConfigurationSection>("clientProviders");

            return ProviderLoader<IConfigurationSettings<TConfigurationObjectType>>.LoadProvider(configSection.Providers, "localSettingsProvider");
		}

		/// <summary>
		/// Retorna o provider de settings remoto
		/// </summary>
		/// <returns>Provider de settings</returns>
        public static IConfigurationSettings<TConfigurationObjectType> GetServerConfigurationSettings()
		{
            ProviderConfigurationSection configSection = ApplicationConfiguration.GetCurrent().GetSection<ProviderConfigurationSection>("clientProviders");

            if (ProviderLoader<IConfigurationSettings<TConfigurationObjectType>>.ProviderExists(configSection.Providers, "serverSettingsProvider"))
			{
                return ProviderLoader<IConfigurationSettings<TConfigurationObjectType>>.LoadProvider(configSection.Providers, "serverSettingsProvider");
			}
			else
			{
				return null;
			}
		}
	}
}